package com.siemens.industrial.app;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.mail.MessagingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by David on 2016/10/13.
 */
public class HeartTask implements Runnable {
    private static final String findOneGatewayInfoByClientIdAndMaxTime = "SELECT * FROM siemens.gateway_state where clientId=? and `time` =(SELECT max(time) FROM siemens.gateway_state);";
    private static final String getMailConfig = "select * from `siemens`.system_config where system_key ='mail_config_key'";
    private static final String getMails = "SELECT group_concat(a.email) mails FROM siemens.user_event_relation a where a.event_id=?;";
    private static final String updateGateWayState = "UPDATE `siemens`.`gateway_state` SET `power`='0' WHERE `clientId`=? and`time`=?;";
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String clientId;
    private JdbcTemplate jdbcTemplate;

    public HeartTask(String clientId) {
        this.jdbcTemplate = DBHelper.getJdbcTemplate();
        this.clientId = clientId;
    }

    @Override
    public void run() {
        Map<String, Object> gateWayState;
        try {
            gateWayState = jdbcTemplate.queryForMap(findOneGatewayInfoByClientIdAndMaxTime, clientId);
        } catch (EmptyResultDataAccessException e) {
            gateWayState = null;
        }
        if (gateWayState == null)
            return;

        if (gateWayState.get("clientId") == null || gateWayState.get("time") == null)
            return;

        Date date;
        try {
            date = simpleDateFormat.parse(String.valueOf(gateWayState.get("time")));
        } catch (ParseException e) {
            date = null;
        }
        if (date == null)
            return;
        long time = date.getTime();

        if ((new Date().getTime() - time) / 1000 > 25) {
            // update gateWay state (power->0)
            if (gateWayState.get("power").equals(1)) {
                List<Map<String, Object>> mailConfig = this.getMailConfig();
                Map<String, String> pps = SendMail.buildMailProperties(mailConfig.get(0).get("system_value").toString());
                Map<String, Object> mails = this.getMailsByEvent("6");
                if (mails.get("mails") != null) {
                    String[] mail = (mails.get("mails").toString()).split(",");
                    if (mail.length > 0) {
                        try {
                            SendMail send = new SendMail(pps);
                            String message = "GateWay  " + gateWayState.get("clientId").toString() + "  " + "下线";
                            send.setMailParam("GateWay下线通知", mail, message, pps.get("mailAddress_key"));
                            send.send();
                            jdbcTemplate.update(updateGateWayState, gateWayState.get("clientId"), date);
                        } catch (MessagingException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public List<Map<String, Object>> getMailConfig() {
        return jdbcTemplate.queryForList(getMailConfig);
    }

    public Map<String, Object> getMailsByEvent(String eventId) {
        return jdbcTemplate.queryForMap(getMails, eventId);
    }

}
